﻿using System;
using System.Data;
using VegetableSale.NET.Utils;
using VegetableSale.NET.Entities;
using System.Data.SqlClient;
using Org.BouncyCastle.Utilities.Encoders;
using System.Xml.Linq;

namespace VegetableSale.NET.Dao;

public class UserMapper
{
    public User SelectOne(string username, string password)
    {

        String sql = "select * from user where login_name='" + username + "' and password='" + password + "';";

        DataSet dateSet = MySqlHelper.GetDataSet(sql);
        DataTable dataTable = dateSet.Tables[0];

        foreach (DataRow row in dataTable.Rows)
        {
            uint id = (uint)row[0];
            string login_name = (string)row[1];
            string name = (string)row[2];
            string pwd = (string)row[3];
            string sex = (string)row[4];
            string address = (string)row[5];
            string email = (string)row[6];
            User user = new User(id, login_name, name, pwd, sex, address, email);
            return user;
        }
        return null;
    }

    public List<User> getUserList(QueryDTO queryDTO)
    {
        String sql = "";

        if (queryDTO.Keyword.Equals(""))
        {
            sql = "select * from user;";
        }
        else
        {
            sql = "SELECT * FROM user WHERE username='" + queryDTO.Keyword + "';";
        }

        List<User> Users = new List<User>();

        DataSet dateSet = MySqlHelper.GetDataSet(sql);
        DataTable dataTable = dateSet.Tables[0];

        foreach (DataRow row in dataTable.Rows)
        {
            uint id = (uint)row[0];
            string loginName = (string)row[1];
            string username = (string)row[2];
            string password = (string)row[3];
            string sex = (string)row[4];
            string email = (string)row[5];
            string address = (string)row[6];
            User user = new User(id, loginName, username, password, sex, email, address);
            Users.Add(user);
        }
        return Users;
    }

    public void addUser(User user)
    {

        String sql = "INSERT INTO user (login_name,username,password,sex,email,address) VALUES ('" + user.LoginName + "','" + user.Username + "','" + user.Password + "','" + user.Sex + "','" + user.Email + "','" + user.Address + "');";

        MySqlHelper.ExecuteSql(sql);
    }

    public void userDelete(int userid)
    {
        String sql = "DELETE FROM user WHERE id=" + userid + ";";

        MySqlHelper.ExecuteSql(sql);
    }

    public void userUpdate(User user)
    {
        String sql = "UPDATE user SET login_name='" + user.LoginName + "',username='" + user.Username + "',password='" + user.Password + "',sex='" + user.Sex + "',email='" + user.Email + "',address='" + user.Address + "' WHERE id=" + user.Id + ";";

        MySqlHelper.ExecuteSql(sql);
    }

}

